package io.modifier.basic.compose

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

object TipNotifier {

    private val defScope = MainScope()

    private val _tipEffect = MutableSharedFlow<String>()
    val tipEffect = _tipEffect.asSharedFlow()
    fun notifyTipEvent(event: String) {
        defScope.launch(Dispatchers.IO) { _tipEffect.emit(event) }
    }

    private val _loadingEffect = MutableSharedFlow<Boolean>()
    val loadingEffect = _loadingEffect.asSharedFlow()
    private var resetLoadingJob: Job? = null
    fun notifyLoadingEvent(flag: Boolean, timeoutRest: Boolean = true, timeout: Long = 1000L * 60) {
        defScope.launch(Dispatchers.IO) {
            if (timeoutRest && flag) {
                resetLoadingJob?.cancel()
                resetLoadingJob = defScope.launch(Dispatchers.IO) {
                    delay(timeout)
                    _loadingEffect.emit(false)
                }
            } else {
                resetLoadingJob?.cancel()
                resetLoadingJob = null
            }
            _loadingEffect.emit(flag)
        }
    }

}
